package com.tool.payment.util;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * User: rizenguo
 * Date: 2014/11/1
 * Time: 14:06
 */
public class XMLParser {

    public static String getXmlStrFromMap(Map<String, String> dataMap){
		StringBuilder strBuilder = new StringBuilder();
		strBuilder.append("<xml>");
		Set<String> objSet = dataMap.keySet();
		for (String key : objSet) {
			if (key == null) {
				continue;
			}
			strBuilder.append("\n");
			strBuilder.append("<").append(key.toString()).append(">");
			String value = dataMap.get(key);
			strBuilder.append(value);
			strBuilder.append("</").append(key.toString()).append(">");
		}
		strBuilder.append("\n</xml>");
		return strBuilder.toString();
	}
    
    /**
     * 解析微信发来的请求（XML）
     * 
     * @param request
     * @return
     * @throws Exception
	*/
	public static Map<String, String> parseXml(String xmlstr) throws Exception {
	        // 将解析结果存储在HashMap中
	        Map<String, String> map = new HashMap<String, String>();
	  
	        // 从request中取得输入流
	        InputStream inputStream = new  ByteArrayInputStream(xmlstr.getBytes("UTF-8"));  
	        // 读取输入流
	        SAXReader reader = new SAXReader();
	        Document document = reader.read(inputStream);
	        // 得到xml根元素
	        Element root = document.getRootElement();
	        // 得到根元素的所有子节点
	        List<Element> elementList = root.elements();
	  
	        // 遍历所有子节点
	        for (Element e : elementList)
	            map.put(e.getName(), e.getText());
	  
	        // 释放资源
	        inputStream.close();
	        inputStream = null;
	        return map;
	}
}
